<template>
  <!-- 默认必须为visibility: hidden -->
  <div ref="eleRef" style="visibility: hidden">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import {
  removeObserve,
  buildIntersectionObserver,
  addObserve,
} from "~utils/IntersectionObserverUtil.ts";

const eleRef = ref<HTMLDivElement>();

function callback(entries: IntersectionObserverEntry[]) {
  entries.map((entry) => {
    /*
    当元素和viewport相交时，添加类名，触发对应的animation
    entry.isIntersecting 值为true表示当前元素与根元素相交
     */
    if (entry.isIntersecting && entry.target === eleRef.value) {
      eleRef.value.classList.add("fadeIn");
      // console.log("显示", eleRef.value);
      // 释放掉observer，减少性能负担
      observer?.disconnect();
    }
  });
}
let observer: IntersectionObserver | null = buildIntersectionObserver(callback);
onMounted(() => {
  addObserve<HTMLDivElement>(eleRef.value, observer);
});
onBeforeUnmount(() => {
  removeObserve(eleRef.value, observer, true);
});
</script>

<style scoped lang="scss">
.fadeIn {
  animation: fade-in 1.3s cubic-bezier(0.16, 1, 0.3, 1);
  animation-fill-mode: forwards;
  visibility: visible !important;
}

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(120px) scale(0.98);
  }

  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>
